package com.vf.cloud.common.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import com.jfinal.kit.StrKit;
import com.vf.cloud.common.constant.SecurityConstant;
import lombok.RequiredArgsConstructor;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;

@RequiredArgsConstructor
@Configuration
public class CorsConfig implements Filter {

	private final StringRedisTemplate redisTemplate;

	private CorsConfiguration buildConfig() {
		CorsConfiguration corsConfiguration = new CorsConfiguration();
		corsConfiguration.addAllowedOrigin("*"); // 1允许任何域名使用
		corsConfiguration.addAllowedHeader("*"); // 2允许任何头
		corsConfiguration.addAllowedMethod("*"); // 3允许任何方法（post、get等）
		corsConfiguration.setMaxAge(1800L);// 4.解决跨域请求两次，预检请求的有效期，单位为秒
		return corsConfiguration;
	}

	@Bean
	public CorsFilter corsFilter() {
		UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
		source.registerCorsConfiguration("/**", buildConfig()); // 4
		return new CorsFilter(source);
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {

		HttpServletResponse httpResponse = (HttpServletResponse) response;
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		if (httpRequest.getRequestURI().startsWith("/Renderers/Any") || httpRequest.getRequestURI().startsWith("/login")
				|| httpRequest.getRequestURI().startsWith("/project") || httpRequest.getRequestURI().startsWith("/reg")
				|| httpRequest.getRequestURI().startsWith("/biz/scene/thumbnail")
				|| httpRequest.getRequestURI().startsWith("/updatePwd")
				|| httpRequest.getRequestURI().startsWith("/code")
				|| httpRequest.getRequestURI().startsWith("/TokenExpired")) {
			chain.doFilter(request, response);
		} else {
			String token = httpRequest.getHeader(SecurityConstant.HEADER);
			if (StrKit.isBlank(token)) {
				httpResponse.sendRedirect("/TokenExpired");// 重定向
			} else {
				token = token.replace(SecurityConstant.TOKEN_SPLIT, "");
				String payload = redisTemplate.opsForValue().get(token);
				if (StrKit.isBlank(payload)) {
					httpResponse.sendRedirect("/TokenExpired");// 重定向
				}
			}
			chain.doFilter(request, response);
		}

//		HttpServletResponse httpResponse = (HttpServletResponse) response;
//		HttpServletRequest httpRequest = (HttpServletRequest) request;
//		httpResponse.setHeader("Access-Control-Allow-Origin", httpRequest.getHeader("Origin"));
//		httpResponse.setHeader("Access-Control-Allow-Methods", httpRequest.getMethod());
//		// httpResponse.setHeader("Access-Control-Max-Age", "3600");
//		httpResponse.setHeader("Access-Control-Allow-Headers", httpRequest.getHeader("Access-Control-Request-Headers"));

	}
}